<?php

namespace App\Http\Controllers\Admin;

use App\Models\User;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use App\Http\Requests\LoginRequest;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends AdminController
{
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    protected $maxLoginAttempts = 5;

    protected $lockoutTime = 100;  // 单位 (秒)

    /**
     * The Guard implementation.
     *
     * @var \Illuminate\Contracts\Auth\Guard
     */
    protected $auth;

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->middleware('guest', ['except' => 'getLogout']);
        $this->auth = $auth;
        
    }

    /**
     * Show the application login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function getLogin()
    {
        return view('auth.login');
    }

    // 用户登录
    public function postLogin(LoginRequest $request)
    {
        if (preg_match("/^1[34578]{1}\d{9}$/", $request->input('username'))) {
            $field = 'phone';
        } else {
            $field = filter_var($request->input('username'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
        }

        $request->request->add([$field => $request->input('username')]);

        //认证凭证
        $credentials = $request->only($field, 'password');

        $throttles = $this->isUsingThrottlesLoginsTrait();

        if ($throttles && $this->hasTooManyLoginAttempts($request)) {
            return $this->sendLockoutResponse($request);
        }

        if ($this->auth->validate($credentials)) {
            $user = $this->auth->getLastAttempted();
            if (!$user->status) {
                return back()->withInput()->with('error', '该用户已被冻结，禁止登录');
            }
            $this->auth->login($user, $request->has('remember'));
            return redirect()->intended('admin');
        }

        if ($throttles) {
            $this->incrementLoginAttempts($request);
        }

        return back()->withInput()->with('error', '用户或密码错误');
    }  

    // 
    /**
     * 注销登录
     *
     * @return \Illuminate\Http\Response
     */    
    public function getLogout()
    {
        $this->auth->logout();

        return redirect('auth/login');
    }
}
